<template>
  <div class="article-container">
    <div class="daohang">报修列表</div>
    <hr>
    <!-- 状态筛选 -->
    <el-select v-model="form.repairState" placeholder="请选择状态" class="custom-select" clearable
      @change="handleStatusChange">
      <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    <hr>
    <!-- 数据表格 -->
    <el-table :data="allData" empty-text="暂无数据" style="width: 85%">
      <el-table-column fixed prop="repairNum" label="编号" style="width: 10%" />
      <el-table-column prop="repairInfo" label="区域" style="width: 10%" />
      <el-table-column prop="repairType" label="项目" style="width: 10%" />
      <el-table-column prop="repairUserName" label="报修人" style="width: 10%" />
      <el-table-column prop="appointmentTime" label="预约时间" style="width: 10%" />
      <el-table-column prop="repairPersonName" label="受理人" style="width: 10%" />
      <el-table-column prop="repairTakeTime" label="受理用时" style="width: 10%" />
      <el-table-column prop="state" label="状态" style="width: 10%" />
      <el-table-column fixed="right" label="操作" style="width: 20%" align="center">
        <template #default="scope">
          <el-button link type="primary" size="mini"
            @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
            查看详情
          </el-button>
          <el-button v-if="scope.row.repairState === 1" link type="success" size="mini"
            @click="openStartRepairDialog(scope.row.repairId, scope.row.repairNum)">
            开始维修
          </el-button>
          <el-button v-if="scope.row.repairState === 2" link type="warning" size="mini"
            @click="completeRepair(scope.row.repairId, scope.row.repairNum)">
            完成维修
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <hr>

    <!-- 分页组件 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
      :total="totalItems"></el-pagination>

    <!-- 开始维修弹窗 -->
    <el-dialog v-model="startRepairDialogVisible" width="30%">
      <span>是否申请材料?</span>
      <hr>
      <span slot="footer" class="dialog-footer">
        <el-button @click="startRepairDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="openMaterialDialog">申请材料</el-button>
        <el-button type="primary" @click="confirmStartRepair">不申请材料</el-button>
      </span>
    </el-dialog>

    <!-- 申请材料弹窗 -->
    <el-dialog v-model="materialDialogVisible" width="30%">
      <el-form :model="materialForm" label-width="100px">
        <div v-for="(material, index) in materialForm.materials" :key="index" style="margin-bottom: 10px;">
          <el-form-item label="材料">
            <el-select v-model="material.material" placeholder="请选择材料" @change="handleMaterialChange(material)">
              <el-option v-for="item in materialOptions" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量">
            <el-input v-model="material.quantity" type="number" placeholder="请输入数量" :min="1" :max="getMaxQuantity(material.material)"></el-input>
          </el-form-item>
          <el-button type="danger" size="small" @click="removeMaterial(index)">删除</el-button>
        </div>
        <el-button type="primary" size="small" @click="addMaterial">添加材料</el-button>
      </el-form>
      <hr>
      <span slot="footer" class="dialog-footer">
        <el-button @click="materialDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmMaterialRequest">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElRow,
  ElCol,
  ElButton,
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElDialog,
  ElTabs,
  ElTabPane,
  ElTable,
  ElTableColumn,
  ElPagination,
} from "element-plus";
import axios from 'axios';

export default {
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElRow,
    ElCol,
    ElButton,
    ElBreadcrumb,
    ElBreadcrumbItem,
    ElDialog,
    ElTabs,
    ElTabPane,
    ElTable,
    ElTableColumn,
    ElPagination,
  },
  data() {
    return {
      form: {
        repairState: ''
      },
      statusOptions: [
        { value: 1, label: '已分配' },
        { value: 2, label: '维修中' },
        { value: 3, label: '维修完成' },
        { value: 4, label: '已驳回' },
        { value: 5, label: '已取消' },
        { value: 0, label: '待审核' }
      ],
      area: '',
      project: '',
      unit: '',
      searchContent: '',
      searchContact: '',
      areaOptions: [],
      projectOptions: [],
      unitOptions: [],
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      allData: [],
      currentData: [],
      // 已删除数据的分页相关数据
      currentPageDeleted: 1,
      pageSizeDeleted: 10,
      totalItemsDeleted: 0,
      allDataDeleted: [],
      deletedData: [],
      activeTab: 'undeleted',
      startRepairDialogVisible: false,
      materialDialogVisible: false,
      currentRepairId: '',
      currentRepairNum: '',
      materialForm: {
        materials: [] // 改为数组，存储多个材料
      },
      materialOptions: []
    };
  },
  mounted() {
    this.fetchRepairData();
    this.fetchMaterialOptions();
  },
  methods: {
    handleMaterialChange(material) {
      const selectedMaterial = this.materialOptions.find(item => item.value === material.material);
      if (selectedMaterial) {
        material.materialAllName = selectedMaterial.materialAllName;
      }
    },
    getMaxQuantity(materialCode) {
      const material = this.materialOptions.find(option => option.value === materialCode);
      return material ? material.maxQuantity : 0;  // 返回最大数量，若未找到则返回 0
    },
    navigateToRoute(route) {
      this.$router.push(route);
    },
    async fetchRepairData() {
      const deleted = this.activeTab === 'undeleted' ? 0 : 1;
      const pageNum = this.activeTab === 'undeleted' ? this.currentPage : this.currentPageDeleted;
      const pageSize = this.activeTab === 'undeleted' ? this.pageSize : this.pageSizeDeleted;

      try {
        const response = await axios.post('/repaircenter/repair/selectRepairByWorker', {
          pageNum,
          pageSize,
          repairState: this.form.repairState,
          deleted
        });
        if (response.data.code === 200) {
          if (deleted === 0) {
            this.allData = response.data.data.list;
            this.totalItems = response.data.data.total;
            this.updateCurrentData();
          } else {
            this.allDataDeleted = response.data.data.list;
            this.totalItemsDeleted = response.data.data.total;
            this.updateDeletedData();
          }
        } else {
          this.$message.error("查询维修记录失败");
        }
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else {
          console.error('查询维修记录失败', error);
          this.$message.error("查询维修记录失败");
        }
      }
    },
    updateCurrentData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.currentData = this.allData.slice(start, end);
    },
    updateDeletedData() {
      const start = (this.currentPageDeleted - 1) * this.pageSizeDeleted;
      const end = start + this.pageSizeDeleted;
      this.deletedData = this.allDataDeleted.slice(start, end);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchRepairData(); // 重新获取数据
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchRepairData(); // 重新获取数据
    },
    handleStatusChange(val) {
      this.form.repairState = val;
      this.fetchRepairData(); // 重新获取数据
    },
    selectRepairById(repairId, repairNum) {
      this.$router.push({ name: 'RepairInfo', params: { id: repairId, num: repairNum } });
    },
    openStartRepairDialog(repairId, repairNum) {
      this.currentRepairId = repairId;
      this.currentRepairNum = repairNum;
      this.startRepairDialogVisible = true;
    },
    confirmStartRepair() {
      this.startRepairDialogVisible = false;
      this.startRepair();
    },
    openMaterialDialog() {
      this.startRepairDialogVisible = false;
      this.materialForm.materials = []; // 清空材料列表
      this.materialDialogVisible = true;
    },
    addMaterial() {
      this.materialForm.materials.push({ material: '', quantity: '', materialAllName: '', });
    },
    removeMaterial(index) {
      this.materialForm.materials.splice(index, 1);
    },
    async confirmMaterialRequest() {
      for (const material of this.materialForm.materials) {
        const maxQuantity = this.getMaxQuantity(material.material);
        if (!material.material || material.quantity <= 0 || material.quantity > maxQuantity) {
          this.$message.warning(`材料 "${material.materialAllName}" 的数量必须大于 0 且不超过 ${maxQuantity}`);
          return;
        }
      }
      if (this.materialForm.materials.some(material => !material.material || !material.quantity)) {
        this.$message.warning('请选择材料并输入数量');
        return;
      }
      try {
        const materials = this.materialForm.materials.map(material => ({
          materialCode: material.material,
          repairNum: this.currentRepairNum,
          count: parseInt(material.quantity, 10)
        }));

        const response = await axios.post('/repaircenter/repairMaterial/applyRepairMaterial', materials, {
          headers: {
            token: localStorage.getItem('token') // 假设 token 存储在 localStorage 中
          }
        });
        console.log('材料申请结果', response.data);
        if (response.data.code === 200) {
          this.$message.success('材料申请成功');
        } else {
          this.$message.error('材料申请失败');
        }
        this.materialDialogVisible = false;
        this.startRepair();
        // 重新获取材料选项
        this.fetchMaterialOptions();
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else {
          console.error('材料申请失败', error);
          this.$message.error("材料申请失败");
        }
      }
    },
    async startRepair() {
      const data = new FormData();
      data.append('repairNum', this.currentRepairNum);

      try {
        const response = await axios.put('/repaircenter/repair/underwayRepair', data, {
          headers: {
            token: localStorage.getItem('token') // 假设 token 存储在 localStorage 中
          }
        });
        console.log('开始维修结果', response.data);
        if (response.data.code === 200) {
          this.$message.success('开始维修成功');
        } else {
          this.$message.error('开始维修失败');
        }
        this.fetchRepairData(); // 刷新列表
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else {
          console.error('开始维修失败', error);
          this.$message.error("开始维修失败");
        }
      }
    },
    async fetchMaterialOptions() {
      try {
        const response = await axios.get('/repaircenter/housingMaterial/getHousingMaterialList');
        if (response.data.code === 200) {
          this.materialOptions = response.data.data.map(item => ({
            value: item.materialCode,
            label: `${item.materialAllName} (库存: ${item.inventory})`,
            materialAllName: item.materialAllName,
            maxQuantity: item.inventory
          }));
        } else {
          this.$message.error("获取材料列表失败");
        }
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else {
          console.error('获取材料列表失败', error);
          this.$message.error("获取材料列表失败");
        }
      }
    },
    completeRepair(repairId, repairNum) {
      this.$router.push({ name: 'AnotherPage', params: { id: repairId, num: repairNum } });
    }
  }
};
</script>

<style scoped>
.repair-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-upload__tip {
  line-height: 1.2;
}

.article-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  margin-top: 110px;
}

.daohang {
  width: 83%;
  text-align: left;
  border-bottom: 1px solid #00000017;
  padding-left: 20px;
}

.custom-select {
  width: 200px;
  /* 根据需要调整宽度 */
}

.breadcrumb-icon {
  position: relative;
  bottom: 5px;
  /* 向下偏移 10px */
  right: 5px;
}

.daohang {
  width: 83%;
  text-align: left;
  border-bottom: 1px solid #00000017;
  background: url(../assets/img/icon-location-blue.png) no-repeat 0 8px;
  background-position: 0px, -12px;
  /* 调整位置 */
  padding-left: 20px;
}

.daohang>a {
  color: #0000004d;
}

.daohang>span {
  color: #0000004d;
}

.no-data-container {
  text-align: center;
  padding: 20px;
}

.no-data-image {
  width: 150px;
  /* 调整图片大小 */
  margin-bottom: 10px;
}

.no-data-container p {
  color: #666;
  font-size: 16px;
}
</style>